import axios from 'axios'
import { getToken } from '@/utils/libs'
import { Toast } from 'vant'
const cancelToken = axios.CancelToken
class HttpRequest {
    constructor(baseUrl = baseURL) {
        this.baseUrl = baseUrl
        this.queue = []
    }
    getInsideConfig() {
        const config = {
            baseURL: this.baseUrl,
            headers: {
                //
            }
        }
        return config
    }
    destroy(config) {
        for(let p in this.queue){
            if(this.queue[p].u === config.url + '&' + config.method) { //当当前请求在数组中存在时执行函数体
                this.queue[p].f() //执行取消操作
                this.queue.splice(p, 1) //把这条记录从数组中移除
            }
        }
    }
    interceptors(instance, url) {
        instance.interceptors.request.use(config => {
            this.destroy(config) //在一个ajax发送前执行一下取消操作
            config.cancelToken = new cancelToken((c)=>{
                // 这里的ajax标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
                this.queue.push({ u: config.url + '&' + config.method, f: c });  
            });
            if( config.loading ) {
                config.toastInstance = Toast.loading({
                    mask: true,
                    message: typeof config.loading == 'string' ? config.loading : '加载中...'
                });
            }
            return config
        }, error => {
            return Promise.reject(error)
        })
        instance.interceptors.response.use(res => {
            this.destroy(res.config)
            if(res.config.toastInstance) {
                res.config.toastInstance.clear()
            }
            const { data, status } = res
            if( status == 500 ) {
                // 系统繁忙
                console.log('[系统繁忙]')
                Toast(data.msg || '系统繁忙')
                return false
            }
            if( status == 401 ) {
                // 需要登录
                console.log('[需要登录]')
                var url  = document.location.href
                document.location.href = data.result + '?redirect_url=' + encodeURIComponent(url);
                return false
            }
            if( res.config.showResult && data.status == 1 ) {
                Toast( typeof res.config.showResult == 'string' ? res.config.showResult : (data.msg || '操作成功') );
            }
            if( typeof data.status != 'undefined' && data.status != 1 ) {
                if( res.config.showError ) {
                    Toast(data.msg || '系统错误')
                }
                return Promise.reject(new Error( data.msg || '系统错误' ))
            }
            console.log('[RESPONSE]', data, status, res)
            return { data, status }
        }, error => {
            console.log('[错误]',error.response, error.message)
            var response = error.response || undefined
            if(response){
                var data = response.data || {}
                if(response.config.showError){
                    Toast(data.msg||error.message||'系统错误：'+response.status)
                }
                if( response.status == 401 ) {
                    // 需要登录
                    console.log('[需要登录]')
                    var url  = document.location.href
                    document.location.href = data.result + '?redirect_url=' + encodeURIComponent(url);
                    return false
                }
            }
            return Promise.reject(error)
        })
    }
    request(options) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }

}

export const upload = ({
    file = null,
    data = {},
    success = () => {},
    failed = () => {},
    showResult = true,
    Url = '/api/upload/file'
} = {}) => {
    if (!file) {
        return new Promise((resolve, reject) => {
            reject(new Error('未选择有效文件'))
        })
    }
    let formdata = new FormData()
    formdata.append("file", file)
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            const ele = object[key]
            formdata.append(key, ele)
        }
    }
    let instance = axios.create({
        baseURL: '',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        withCredentials: true,
        timeout: 20000
    });
    return new Promise((resolve, reject) => {
        instance.post(Url, formdata).then(res => {
            console.log('UPLOAD_RES', res)
            var resData = res.data            
            if (resData.status < 1) {                
                Toast(resData.msg || '上传失败')
                reject(new Error(resData.msg || '上传失败'))
            } else {
                if (showResult) {
                    Toast(typeof showResult == 'string' ? showResult : '上传成功')
                }
                success(resData)
                resolve(resData)
            }
        }).catch(error => {
            Toast('上传失败')
            console.log(error)
            reject(error)
        })
    })
}

export default HttpRequest
